<?php

class Backdoor_UserController extends Zend_Controller_Action {

    protected $_statusMessenger = null;
    protected $_errorMessenger = null;
    protected $_username = null;
    protected $_userMapper = null;
    protected $user;
    protected $language;

    public function init() {
        $this->_statusMessenger = $this->_helper->flashMessenger;
        $this->_errorMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
        $this->_errorMessenger->setNamespace('error');
        $this->view->statusMessages = $this->_statusMessenger->getMessages();
        $this->view->errorMessages = $this->_errorMessenger->getMessages;

        $this->username = $this->_request->getParam('user');
        $this->view->documentClasses = array('backdoor', 'user');
        $this->view->username = $this->_request->getParam('user');

        $locale = new Zend_Locale();
        if ($locale->getLanguage() == 'de') {
            $this->language = 'name_de';
        } else {
            $this->language = 'name_en';
        }
    }

    public function indexAction() {
        $userMapper = new Application_Model_UserMapper();
        $this->view->users = $userMapper->fetchAll();
    }

    protected function _getUser() {
        $this->_userMapper = new Application_Model_UserMapper();
        $this->user = new Application_Model_UserModel();
        $this->user = $this->_userMapper->fetchOne(array('username = ?' => $this->username));

        $this->user = $this->_userMapper->find($this->user->getId(), new Application_Model_UserModel);


        if (null === $this->user) {
            $this->_errorMessenger->addMessage('Benutzer nicht gefunden.');
            $this->_redirect('/backdoor/user');
        }
    }

    public function createAction() {
        $this->view->form = $this->_getCreateForm();
        var_dump("wwasdasdasdasdasdadasdad");
        $post = $this->_request->getPost();
        if ($post) {
            if (!$this->view->form->isValid($post)) {
                $this->view->form->populate($post);
            } elseif ($post['password'] != $post['password_repeat']) {
                $this->view->form->password_repeat->addError('the passwords are not the same');
                $this->view->form->populate($post);
            } else {
                // verarbeite Daten

                $values = $this->view->form->getValues();
                $values['username'] = $values['username'];
                $values['password'] = md5($values['password']);
                $tempuser = new Application_Model_UserModel($values);
                $tempuser->getMapper()->save($tempuser);

                if (null !== $tempuser->id) {
                    $this->_statusMessenger->addMessage(
                            'Benutzer ' . $tempuser->username . ' gespeichert.'
                    );
                } else {
                    $this->_errorMessenger->addMessage(
                            'Fehler beim Speichern von ' . $tempuser->username
                    );
                }

                $this->_redirect('/backdoor/user');
            }
        }
    }

    public function editAction() {
        $this->_getUser();

        $this->view->form = $this->_getUserForm();
        $this->view->form->setDefaults($this->user->toArray());
        $post = $this->_request->getPost();


        if ($post) {
            if (!$this->view->form->isValid($post)) {
                $this->view->form->populate($post);
            } elseif ($post['password'] != $post['password_repeat']) {
                $this->view->form->password_repeat->addError($this->view->translate('the passwords are not the same.'));
                $this->view->form->populate($post);
            } else {
                $values = $this->view->form->getValues();

                $tempuser = new Application_Model_UserModel($values);
                $tempuser->setId($this->user->getId());

                $this->_userMapper->save($tempuser);
                var_dump($tempuser);

                if (null !== $tempuser->id) {
                    $this->_statusMessenger->addMessage(
                            $this->view->translate('Update complete.')
                    );
                } else {
                    $this->_errorMessenger->addMessage(
                            $this->view->translate('Error while updating!')
                    );
                }

                $this->_redirect('/backdoor/user');
            }
        }
    }

    public function deleteAction() {
        $this->_getUser();

        $this->_userMapper->delete($this->user->getId());
        $this->_redirect('/backdoor/user');
    }

    protected function _getUserForm() {
        $form = new Zend_Form();


        $table = new Application_Model_ColorMapper();
        $table = $table->fetchFree();

        $colorSelect = new Zend_Form_Element_Radio('color');
        $colorSelect->setLabel(_('Choose color'));

// TODO: sehr hässlich
        $number = $this->user->id;
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = new Zend_Db_Select($db);
        $select->from('color', array('id', 'hex', 'name_en', 'name_de'))
                ->joinLeft('user', 'color.hex = user.color', array())
                ->where('user.color IS NULL')
                ->orWhere('user.id = ?', $number);
        $resultSet = $db->fetchAll($select);

        foreach ($resultSet as $c) {
            $colorSelect->addMultiOption($c['hex'], $c[$this->language]);
        }

        $form->setMethod(Zend_Form::METHOD_POST);
        $form->addElements(array(
            array('text', 'salutation', array(
                    'label' => _('Name'),
                    'size' => '32'
            )),
            array('radio', 'gender', array(
                    'label' => _('Gender'),
                    'size' => '32',
                    // 'decorators'=> array('ViewHelper'), 
                    'multiOptions' => array(
                        m => _('male'),
                        f => _('female'),
                    ),
                    'separator' => ' '
            )),
        ));

        $form->addElement($colorSelect);
        $form->addElements(array(
            array('text', 'username', array(
                    'label' => _('Username'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        array('regex', false, '/^[a-zA-Z0-9_]+$/'),
                        array('StringLength', false, 4)
                    )
            ))
        ));
        $form->addElements(array(
            array('password', 'password', array(
                    'label' => _('Password'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        array('StringLength', false, 8) // aendern!
                    )
            )),
            array('password', 'password_repeat', array(
                    'label' => _('Repeat Password'),
                    'size' => '32',
                    'required' => true
            )),
            array('text', 'email', array(
                    'label' => _('E-Mail-Adress'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        'EmailAddress'
                    )
            )),
            array('submit', 'submit', array(
                    'label' => _('Save'),
                    'decorators' => array('ViewHelper')
            ))
        ));

        $this->translatePlaceholder($form);
        return $form;
    }

    /**
     * Erstellt Registrierungs Formular
     * 
     * Weiterleitung nach /index
     * 
     *  @return $form Zend_Form Registierung
     */
    protected function _getCreateForm() {
        $form = new Zend_Form();


        $table = new Application_Model_ColorMapper();
        $table = $table->fetchFree();

        $colorSelect = new Zend_Form_Element_Radio('color');
        $colorSelect->setLabel(_('Choose color'));

// TODO: sehr hässlich

        $db = Zend_Db_Table::getDefaultAdapter();
        $select = new Zend_Db_Select($db);
        $select->from('color', array('id', 'hex', 'name_en', 'name_de'))
                ->joinLeft('user', 'color.hex = user.color', array())
                ->where('user.color IS NULL');
        $resultSet = $db->fetchAll($select);

        foreach ($resultSet as $c) {
            $colorSelect->addMultiOption($c['hex'], $c[$this->language]);
        }

        $form->setMethod(Zend_Form::METHOD_POST);
        $form->addElements(array(
            array('text', 'salutation', array(
                    'label' => _('Name'),
                    'size' => '32'
            )),
            array('radio', 'gender', array(
                    'label' => _('Gender'),
                    'size' => '32',
                    // 'decorators'=> array('ViewHelper'), 
                    'multiOptions' => array(
                        m => _('male'),
                        f => _('female'),
                    ),
                    'separator' => ' '
            )),
        ));

        $form->addElement($colorSelect);
        $form->addElements(array(
            array('text', 'username', array(
                    'label' => _('Username'),
                    'placeholder' => _('Your login name'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        array('regex', false, '/^[a-zA-Z0-9_]+$/'),
                        array('StringLength', false, 4)
                    )
            ))
        ));
        $form->addElements(array(
            array('password', 'password', array(
                    'label' => _('Password'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        array('StringLength', false, 8) // aendern!
                    )
            )),
            array('password', 'password_repeat', array(
                    'label' => _('Repeat Password'),
                    'size' => '32',
                    'required' => true
            )),
            array('text', 'email', array(
                    'label' => _('E-Mail-Adress'),
                    'size' => '32',
                    'required' => true,
                    'validators' => array(
                        'EmailAddress'
                    )
            )),
            array('submit', 'submit', array(
                    'label' => _('save'),
                    'decorators' => array('ViewHelper')
            ))
        ));
        $form->getElement('email')->addValidator('Db_NoRecordExists', false, array(
            'table' => 'user',
            'field' => 'email',
            'messages' => array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => _('Address allready used'))
        ));
        $form->getElement('email')->addValidator('Db_NoRecordExists', false, array(
            'table' => 'user',
            'field' => 'email',
            'messages' => array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => _('Address allready used'))
        ));

        $form->getElement('username')->addValidator('Db_NoRecordExists', false, array(
            'table' => 'user',
            'field' => 'username',
            'messages' => array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => _('Usersame allready used'))
        ));
        $this->translatePlaceholder($form);
        return $form;
    }

    /**
     * Übersetzt die placeholder in der From 
     * @param type $form ZendFrom 
     */
    private function translatePlaceholder($form) {
        foreach ($form->getElements() as $key => $element) {
            $placeholder = $element->getAttrib('placeholder');
            if (isset($placeholder)) {
                $form->$key->setAttrib('placeholder', $this->view->translate($placeholder));
            }
        }
    }

}

